//
//  NetworkingHandle.m
//  PetAPP
//
//  Created by dllo on 16/1/25.
//  Copyright © 2016年 Yuming. All rights reserved.
//

#import "NetworkingHandle.h"

@implementation NetworkingHandle

+ (void)handleWorkData:(NSString *)URL AndBody:(NSString *)body value:(NSDictionary *)valueDic handleBlock:(void (^)(id result))block {
    /** url转码防止有汉字 */
    NSString *str = [URL stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    /** 创建url*/
    NSURL *url = [NSURL URLWithString:str];
    /** 创建可变请求 */
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    if (body == nil) {
        /** 方法post */
        request.HTTPMethod = @"GET";
        /** body如果是get可为空 */
        request.HTTPBody = nil;
    }else {
        /** 方法post */
        request.HTTPMethod = @"POST";
        /** body如果是get可为空 */
        request.HTTPBody = [body dataUsingEncoding:NSUTF8StringEncoding];
    }
    if (valueDic != nil) {
        for (NSString *key in valueDic) {
            [request addValue:[valueDic objectForKey:key] forHTTPHeaderField:key];
        }
    }

    /** 创建连接通道 */
    NSURLSession *session = [NSURLSession sharedSession];
    /** 创建任务 */
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        NSError *errorJSON = nil;
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorJSON];
        dispatch_async(dispatch_get_main_queue(), ^{
            block(result);
        });        
        
    }];
    /** 开始任务 */
    [task resume];

}

@end
